<template>
  <div class="picture-upload">
    <a-upload
      list-type="picture-card"
      :show-upload-list="false"
      :custom-request="handleUpload"
      :before-upload="beforeUpload"
    >
      <img v-if="picture?.url" :src="picture?.url" alt="图片解析出错，请稍候重试" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击或拖拽上传图片文件</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { uploadPictureByFileUsingPost } from '@/api/pictureController.ts'

const loading = ref<boolean>(false)

/**
 * Props 接口定义了组件期望接收两个 props：picture，onSuccess。
 * 通过 defineProps<Props>()，组件就可以接收并按照这个类型定义来校验传入的 props。
 */
interface Props {
  picture?: API.PictureVO
  // 图片上传成功后 通过这个函数传递新的图片返回展示
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()

/**
 * 图片文件上传
 * @param file
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const params: API.PictureUploadRequest = props.picture ? { id: props.picture.id } : {}
    params.spaceId = props.spaceId
    const res = await uploadPictureByFileUsingPost(params, {}, file)
    // @ts-ignore
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      // @ts-ignore
      props.onSuccess?.(res.data.data)
    } else {
      // @ts-ignore
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    // @ts-ignore
    message.error('图片上传失败，' + error.message)
  }
  loading.value = false
}

/**
 * 调用后端上传图片前的前端校验
 * @param file
 */
// @ts-ignore
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 校验图片格式
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/jpg' ||
    file.type === 'image/webp' ||
    file.type === 'image/bmp' ||
    file.type === 'image/svg'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，可选格式有 jpeg、png、jpg、webp、bmp')
  }
  // 校验图片大小
  const isLt2M = file.size / 1024 / 1024 < 20
  if (!isLt2M) {
    message.error('不能上传超过 20M 的图片')
  }
  return isJpgOrPng && isLt2M
}
</script>
<style scoped>
.picture-upload :deep(.ant-upload) {
  width: 100% !important;
  height: 100% !important;
  min-width: 152px;
  min-height: 152px;
}

.picture-upload img {
  max-width: 100%;
  max-height: 360px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
